package com.fire.control.system.module.company.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import com.fire.control.system.config.redis.RedisService;
import com.fire.control.system.dto.CompanyResultDTO;
import com.fire.control.system.dto.UserDTO;
import com.fire.control.system.entity.Company;
import com.fire.control.system.entity.DeviceType;
import com.fire.control.system.entity.Role;
import com.fire.control.system.entity.User;
import com.fire.control.system.module.company.dao.CompanyMapper;
import com.fire.control.system.module.company.dao.ManagementMapper;
import com.fire.control.system.module.company.dao.ManagementRepository;
import com.fire.control.system.module.company.service.IManagementService;
import com.fire.control.system.module.device.dao.DeviceGroupRepository;
import com.fire.control.system.module.login.service.impl.LoginServiceImpl;
import com.fire.control.system.module.role.dao.RoleMapper;
import com.fire.control.system.module.role.service.IRoleService;
import com.fire.control.system.module.system.dao.RoleRepository;
import com.fire.control.system.module.user.dao.UserRepository;
import com.fire.control.system.module.warning.service.WarningService;
import com.fire.control.system.statics.ResponseMessage;
import com.fire.control.system.statics.Type_Company;
import com.fire.control.system.statics.Type_Role;
import com.fire.control.system.statics.Type_User;
import com.fire.control.system.support.protocol.comman.ProtocolSelector;
import com.fire.control.system.support.protocol.comman.ResponseProtocol;
import com.fire.control.system.support.protocol.management.ManagementRequestProtocol;
import com.fire.control.system.support.util.ResultPageUtil;
import com.fire.control.system.support.util.SmsUtil;
import com.fire.control.system.support.util.XdaoDate;
import com.fire.control.system.support.util.XdaoPassword;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class ManagementServiceImpl implements IManagementService {
	public static final Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);

	@Autowired
	private ManagementRepository managementRepository;

	@Autowired
	private UserRepository userRepository;

	private DeviceGroupRepository deviceGroupRepository;
	@Autowired
	private ProtocolSelector protocolSelector;

	@Autowired
	private ManagementMapper managementMapper;

	@Autowired
	private CompanyMapper companyMapper;

	@Autowired
	private SmsUtil smsUtil;

	@Autowired
	private ResultPageUtil resultPageUtil;

	@Autowired
	private RedisService redisService;

	@Autowired
	private WarningService warningService;
	
	@Autowired
	private IRoleService roleService;
	
	@Autowired
	private RoleRepository roleRepository;

	@Autowired
	private RoleMapper roleMapper;
	/**
	 * <p>
	 * Title: getManagementListByCondition
	 * </p>
	 * <p>
	 * Description: 模糊查询企业列表
	 * </p>
	 * 
	 * @param requestProtocol
	 * @param p
	 * @return
	 * @see com.fire.control.system.module.company.service.IManagementService#getManagementListByCondition(com.fire.control.system.support.protocol.management.ManagementRequestProtocol,
	 *      com.xdao.framework.persistence.utils.Pagination)
	 */
	@Override
	public ResponseProtocol getManagementListByCondition(ManagementRequestProtocol requestProtocol) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);

		PageHelper.startPage(requestProtocol.getPage(), requestProtocol.getSize());

		List<CompanyResultDTO> companyList = companyMapper.getCompanyByCondition(requestProtocol);

		Map<String, Object> returnMap = resultPageUtil.resultPage(new PageInfo<CompanyResultDTO>(companyList),
				companyList);
		if (!returnMap.isEmpty()) {
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("数据返回成功!");
			response.setDate(new XdaoDate());
			response.setData(returnMap);
		} else {
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("成功调取但无数据!");
		}
		return response;
	}

	/**
	 * <p>
	 * Title: getDeviceGroups
	 * </p>
	 * <p>
	 * Description: 获取设备组
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.company.service.IManagementService#getDeviceGroups(com.fire.control.system.support.protocol.management.ManagementRequestProtocol)
	 */
	@Override
	public ResponseProtocol getDeviceTypeList(ManagementRequestProtocol requestProtocol, HttpServletRequest request) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);

		List<DeviceType> deviceTypeList = managementMapper.deviceTypeList();

		if (!deviceTypeList.isEmpty() && deviceTypeList.size() > 0) {
			ResponseMessage.CODE_200.messageToProtocol(response);
			response.setData(deviceTypeList);
		} else {
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("成功调取但无数据!");
		}
		return response;
	}

	/**
	 * <p>
	 * Title: saveManagementInfo
	 * </p>
	 * <p>
	 * Description: 添加单位
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.company.service.IManagementService#saveManagementInfo(com.fire.control.system.support.protocol.management.ManagementRequestProtocol)
	 */
	@Override
	public ResponseProtocol saveManagementInfo(ManagementRequestProtocol requestProtocol, UserDTO u) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);

		User users = userRepository.findOne(u.getUserId());
		Company c = requestProtocol.getCompany();
		String provinceId = requestProtocol.getCompany().getProvinceId();
		String cityId = requestProtocol.getCompany().getProvinceId();
		String areaId = requestProtocol.getCompany().getAreaId();

		User user = new User();
		String deviceType = requestProtocol.getCompany().getDeviceType();
		String loginName = requestProtocol.getLoginName();
		Type_Company companyType = requestProtocol.getCompany().getCompanyType();

		String password = XdaoPassword.getPassword();
		user.setId(UUID.randomUUID().toString());
		user.setName(c.getContact());
		user.setLoginName(loginName);
		user.setEnable(true);
		user.setPassword(XdaoPassword.encrypt(password));
		user.setUserType(Type_User.manager.toString());
		user.setTelNumber(c.getTelNumber());
		
		//给用户赋予角色
		Role r = new Role();
		if(companyType.equals(Type_Company.facilitator)){
			r.setId(Type_Role.service_manager.getId());
			r.setRoleName(Type_Role.service_manager.getText());
			r.setRoleType(Type_Role.service_manager.toString());
		}else if(companyType.equals(Type_Company.operating_company)){
			r.setId(Type_Role.operator_manager.getId());
			r.setRoleName(Type_Role.operator_manager.getText());
			r.setRoleType(Type_Role.operator_manager.toString());
		}else if(companyType.equals(Type_Company.building_user)){
			r.setId(Type_Role.unit_manager.getId());
			r.setRoleName(Type_Role.unit_manager.getText());
			r.setRoleType(Type_Role.unit_manager.toString());
		}
		c.setDeviceType(deviceType);
		c.setCompanyType(companyType);
		c.setStatus(true);
		c.setEnable(true);
		c.setProvinceId(provinceId);
		c.setCityId(cityId);
		c.setAreaId(areaId);
		c.setParentId(users.getCompany().getId());
		user.setCompany(c);

		if (Type_Company.facilitator.equals(companyType)) {
			warningService.addDefaultMsgPushSet(c.getId());
		}

		if (Type_Company.operating_company.equals(companyType) || Type_Company.building_user.equals(companyType)) {
			c.setParentId(users.getCompany().getId());
		}
		
		Company retrunCompany = managementRepository.saveAndFlush(c);
		
		if (retrunCompany != null) {
			User returnUser = userRepository.save(user);
			//插入用户角色管理
			roleMapper.addUserRole(returnUser.getId(), r.getId());
			if (returnUser != null) {
				// 发送密码给用户
				smsUtil.sendSmsPwd(c.getTelNumber(), loginName, password);
				ResponseMessage.CODE_200.messageToProtocol(response).setMessage("单位添加成功!");
				response.setDate(new XdaoDate());
				response.setData(returnUser);
			}
		} else {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("单位添加失败!");
			response.setDate(new XdaoDate());
		}
		return response;
	}

	/**
	 * <p>
	 * Title: deleteManagementInfo
	 * </p>
	 * <p>
	 * Description: 删除选中的企业信息
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.company.service.IManagementService#deleteManagementInfo(com.fire.control.system.support.protocol.management.ManagementRequestProtocol)
	 */
	@Override
	public ResponseProtocol deleteManagementInfo(ManagementRequestProtocol requestProtocol) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);
		int n = 0;
		Company deleteCompany = null;
		List<String> ids = requestProtocol.getId();

		List<Company> companyList = managementRepository.findAll(ids);

		for (Company c : companyList) {
			c.setStatus(false);
			deleteCompany = managementRepository.saveAndFlush(c);
			n++;
		}

		if (n <= 0) {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("单位删除失败!");
			response.setDate(new XdaoDate());
		} else {
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("单位删除成功!");
			;
			response.setDate(new XdaoDate());
			response.setData(deleteCompany);
		}
		return response;
	}

	/**
	 * <p>
	 * Title: updateManagementInfo
	 * </p>
	 * <p>
	 * Description: 修改企业信息
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.company.service.IManagementService#updateManagementInfo(com.fire.control.system.support.protocol.management.ManagementRequestProtocol)
	 */
	@Override
	public ResponseProtocol updateManagementInfo(ManagementRequestProtocol requestProtocol, UserDTO user) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);
		Company c = null;
		for (String id : requestProtocol.getId()) {
			c = managementRepository.findOne(id);
		}
		Company updateCompany = requestProtocol.getCompany();
		updateCompany.setParentId(c.getParentId());
		c.setCompany(updateCompany);

		Company returnCompany = managementRepository.saveAndFlush(c);
		if (!returnCompany.equals(null)) {
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("单位修改成功!");
			response.setDate(new XdaoDate());
			response.setData(returnCompany);
		} else {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("单位修改失败!");
			response.setDate(new XdaoDate());
		}
		return response;
	}

	/**
	 * <p>
	 * Title: updateManagementStatus
	 * </p>
	 * <p>
	 * Description: 修改单位状态
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.company.service.IManagementService#openCompany(com.fire.control.system.support.protocol.management.ManagementRequestProtocol)
	 */
	@Override
	@Transactional
	public ResponseProtocol updateManagementStatus(ManagementRequestProtocol requestProtocol) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);
		Collection<Company> companyList = new ArrayList<Company>();
		Company c = null;
		for (String id : requestProtocol.getId()) {
			c = managementRepository.findOne(id);
			companyList.add(c);
		}
		Company updateCompany = requestProtocol.getCompany();

		for (Company company : companyList) {
			company.setEnable(updateCompany.isEnable());
		}

		List<Company> retrunCompany = managementRepository.save(companyList);
		if (!retrunCompany.equals(null)) {
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("单位状态修改成功!");
			response.setDate(new XdaoDate());
			response.setData(retrunCompany);
		} else {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("单位状态修改失败!");
			response.setDate(new XdaoDate());
		}
		return response;
	}

	/**
	 * @author liuxincheng
	 * @Title: buildPageRequest
	 * @Description: TODO(构建分页请求)
	 * @param @param
	 *            pageNumber
	 * @param @param
	 *            pagzSize
	 * @param @return
	 *            设定文件
	 * @return PageRequest 返回类型
	 * @throws null
	 */
	private PageRequest buildPageRequest(int pageNumber, int pagzSize) {
		return new PageRequest(pageNumber - 1, pagzSize, null);
	}

	/**
	 * <p>
	 * Title: getParentCompany
	 * </p>
	 * <p>
	 * Description: 获得上层单位
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.company.service.IManagementService#getParentCompany(com.fire.control.system.support.protocol.management.ManagementRequestProtocol)
	 */
	@Override
	public ResponseProtocol getParentCompany(ManagementRequestProtocol requestProtocol, UserDTO user) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);

		String parentId = user.getCompany().getParentId();

		List<Company> companyList = companyMapper.getParentCompany(parentId);

		if (!companyList.isEmpty() && companyList.size() > 0) {
			response.setData(companyList);
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("数据返回成功!");
		} else {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("数据返回失败!");
		}
		return response;
	}

	/**
	 * <p>
	 * Title: getUserListByCompanyId
	 * </p>
	 * <p>
	 * Description: 根据企业Id获取用户列表
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.company.service.IManagementService#getUserListByCompanyId(com.fire.control.system.support.protocol.management.ManagementRequestProtocol)
	 */
	@Override
	public ResponseProtocol getUserListByCompanyId(ManagementRequestProtocol requestProtocol) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);

		String companyId = requestProtocol.getCompanyId();

		List<User> userList = companyMapper.getUserListByCompanyId(companyId);

		if (!userList.isEmpty() && userList.size() > 0) {
			response.setData(userList);
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("数据返回成功!");
		} else {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("数据返回失败!");
		}
		return response;
	}

	/**
	 * <p>
	 * Title: getCheckManagementList
	 * </p>
	 * <p>
	 * Description: 获得选中单位信息
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.company.service.IManagementService#getCheckManagementList(com.fire.control.system.support.protocol.management.ManagementRequestProtocol)
	 */
	@Override
	public ResponseProtocol getCheckManagementList(ManagementRequestProtocol requestProtocol) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);

		List<CompanyResultDTO> companyDTO = companyMapper.getCheckManagementList(requestProtocol);

		if (companyDTO != null) {
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("数据返回成功!");
			response.setDate(new XdaoDate());
			response.setData(companyDTO.get(0));
		} else {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("数据返回失败!");
		}
		return response;
	}
}
